//package com.example.mybatisplus.web.controller;
//
//import org.springframework.web.bind.annotation.*;
//import org.springframework.web.client.RestTemplate;
//import org.springframework.http.*;
//import org.springframework.web.client.HttpClientErrorException;
//
//import java.util.HashMap;
//import java.util.Map;
//
//@RestController
//@RequestMapping("/api/ai")
//public class AIController {
//
//    private final String DASHSCOPE_API_KEY = "sk-1c2a6912fd59413c8c6e00da0fd95853"; // 替换为你的 API Key
//    private final String DASHSCOPE_API_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
//
//    @PostMapping("/chat")
//    public String chat(@RequestBody Map<String, Object> requestBody) {
//        RestTemplate restTemplate = new RestTemplate();
//
//        // 请求头
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_JSON);
//        headers.set("Authorization", "Bearer " + DASHSCOPE_API_KEY);
//
//        // 构建请求体
//        Map<String, Object> requestBodyMap = new HashMap<>();
//        requestBodyMap.put("model", "qwq-32b");
//        requestBodyMap.put("stream", true);
//
//        Map<String, String> message = new HashMap<>();
//        message.put("role", "user");
//        message.put("content", requestBody.get("message").toString());
//
//        requestBodyMap.put("messages", new Map[]{message});
//
//        // 发送请求
//        HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBodyMap, headers);
//        try {
//            ResponseEntity<String> response = restTemplate.postForEntity(DASHSCOPE_API_URL, request, String.class);
//            return response.getBody();
//        } catch (HttpClientErrorException e) {
//            return "请求失败: " + e.getResponseBodyAsString();
//        }
//    }
//}
package com.example.mybatisplus.web.controller;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.*;
import org.springframework.web.client.HttpClientErrorException;

import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;


import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.*;
import org.springframework.web.client.HttpClientErrorException;

import org.json.JSONObject;

@RestController
@RequestMapping("/api/ai")
public class AIController {

    private final String DASHSCOPE_API_KEY = "sk-1c2a6912fd59413c8c6e00da0fd95853"; // 替换为你的 API Key
    private final String DASHSCOPE_API_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";

    @PostMapping("/chat")
    public String chat(@RequestBody Map<String, Object> requestBody) {
        RestTemplate restTemplate = new RestTemplate();

        // 请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + DASHSCOPE_API_KEY);

        // 构建请求体
        Map<String, Object> requestBodyMap = new HashMap<>();
        requestBodyMap.put("model", "qwq-32b");
        requestBodyMap.put("stream", true);

        Map<String, String> message = new HashMap<>();
        message.put("role", "user");
        message.put("content", requestBody.get("message").toString());

        requestBodyMap.put("messages", new Map[]{message});

        // 发送请求
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBodyMap, headers);
        try {
            ResponseEntity<String> response = restTemplate.postForEntity(DASHSCOPE_API_URL, request, String.class);
            String responseBody = response.getBody();

            // 提取 reasoning_content 的内容
            String result = extractReasoningContent(responseBody);
            return result;
        } catch (HttpClientErrorException e) {
            return "请求失败: " + e.getResponseBodyAsString();
        }
    }

    private String extractReasoningContent(String jsonResponse) {
        StringBuilder result = new StringBuilder();

        // 按行分割响应内容
        String[] lines = jsonResponse.split("\n");

        for (String line : lines) {
            // 去除每行的前缀 "data: "（如果存在）
            line = line.trim();
            if (line.startsWith("data: ")) {
                line = line.substring(6).trim();
            }

            // 解析每一行的 JSON 对象
            try {
                JSONObject jsonObject = new JSONObject(line);
                if (jsonObject.has("choices")) {
                    JSONArray choices = jsonObject.getJSONArray("choices");
                    for (int i = 0; i < choices.length(); i++) {
                        JSONObject choice = choices.getJSONObject(i);
                        if (choice.has("delta") && choice.getJSONObject("delta").has("reasoning_content")) {
                            String reasoningContent = choice.getJSONObject("delta").getString("reasoning_content");
                            result.append(reasoningContent);
                        }
                    }
                }
            } catch (Exception e) {
                // 忽略解析失败的行
                continue;
            }
        }

        return result.toString();
    }
}
